//
//  ZJSGuideView.m
//  ZJS
//
//  Created by so on 16/10/28.
//  Copyright © 2016年 zall. All rights reserved.
//

#import "ZJSGuideView.h"

static NSString * const ZJSGuideDidShowKey = @"ZJSGuideDidShowKey";
static NSString * const ZJSGuideCollectionViewCellIdentifier = @"ZJSGuideCollectionViewCellIdentifier";

@interface ZJSGuideCollectionViewCell : UICollectionViewCell
@property (strong, nonatomic, readonly) UIImageView *imageView;
@property (strong, nonatomic, readonly) UIButton *bottombtn;
@end
@implementation ZJSGuideCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _imageView.backgroundColor = [UIColor clearColor];
        _bottombtn = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth - 165.f * (ScreenWidth / 375.f)) / 2.f,ScreenHeight - 165.f * (ScreenWidth / 375.f), 165.f * (ScreenWidth / 375.f), 55.f * (ScreenWidth / 375.f))];
        [self addSubview:self.imageView];
        [self addSubview:self.bottombtn];

    }
    return (self);
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = self.bounds;
    self.bottombtn.frame = CGRectMake((ScreenWidth - 165.f * (ScreenWidth / 375.f)) / 2.f,ScreenHeight - 165.f * (ScreenWidth / 375.f), 165.f * (ScreenWidth / 375.f), 55.f * (ScreenWidth / 375.f));
}
@end

@interface ZJSGuideView () <UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate> {
    BOOL _needRemoveSelf;
}

@property (strong, nonatomic, readonly) UIPageControl *pageControl;

@property (copy, nonatomic) NSArray <NSString *> *imagesNamed;

@property (copy, nonatomic) void(^dismissBlock)(void);

@property (strong, nonatomic, readonly) UICollectionView *collectionView;

@end


@implementation ZJSGuideView
@synthesize collectionView = _collectionView;
@synthesize pageControl = _pageControl;

#pragma mark - life cycle
/**
 *  @brief  展示引导页，anyway为NO时只有第一次展示，anyway为YES则任何情况都展示
 */
+ (BOOL)showInView:(UIView *)inView anyway:(BOOL)anyway dismissBlock:(void(^)(void))dismissBlock {
    return ([self showImages:@[@"6.27_1", @"6.27_2",@"6.27_3"] inView:inView anyway:anyway dismissBlock:dismissBlock]);
}

/**
 *  @brief  展示引导页，images为指定图片，anyway为NO时只有第一次展示，anyway为YES则任何情况都展示
 */
+ (BOOL)showImages:(NSArray <NSString *> *)images inView:(UIView *)inView anyway:(BOOL)anyway dismissBlock:(void(^)(void))dismissBlock {
    if([images count] == 0) {
        return (NO);
    }
    
    if(!anyway) {
        NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] stringObjectForKey:@"CFBundleShortVersionString"];
        NSString *didShowLastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:ZJSGuideDidShowKey];
        BOOL same = (appVersion && didShowLastVersion && [appVersion isEqualToString:didShowLastVersion]);
        if(same) {
            return (NO);
        }
    }
    
    if(!inView) {
        inView = [[UIApplication sharedApplication] keyWindow];
    }
    [inView endEditing:YES];
    ZJSGuideView *guideView = [[ZJSGuideView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    guideView.imagesNamed = images;
    guideView.dismissBlock = dismissBlock;
    [inView addSubview:guideView];
    return (YES);
}

/**
 *  @brief  内存释放
 */
- (void)dealloc {
    
}

/**
 *  @brief  初始化
 */
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        _needRemoveSelf = NO;
        [self addSubview:self.collectionView];
        //暂时隐藏  2017.5.28  张峰
        [self addSubview:self.pageControl];
        [self bringSubviewToFront:self.pageControl];
    }
    return (self);
}
#pragma mark -

#pragma mark - override
/**
 *  @brief  重新布局
 */
- (void)layoutSubviews {
    [super layoutSubviews];
    self.collectionView.frame = UIEdgeInsetsInsetRect(self.bounds, self.contentInsets);
    self.pageControl.center = CGPointMake(self.width / 2.0f, self.height - 40.0f);
}
#pragma mark -

#pragma mark - setter
/**
 *  @brief  设置图片
 */
- (void)setImagesNamed:(NSArray<NSString *> *)imagesNamed {
    [self willChangeValueForKey:@"imagesNamed"];
    _imagesNamed = [imagesNamed copy];
    [self didChangeValueForKey:@"imagesNamed"];
    self.pageControl.numberOfPages = [imagesNamed count];
    self.pageControl.hidden = ([imagesNamed count] <= 1);
    [self.collectionView reloadData];
    [self setNeedsLayout];
}
#pragma mark -

#pragma mark - getter
/**
 *  @brief  表格的懒加载
 */
- (UICollectionView *)collectionView {
    if(!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.minimumLineSpacing = 0.0f;
        flowLayout.minimumInteritemSpacing = 0.0f;
        flowLayout.sectionInset = UIEdgeInsetsZero;
        _collectionView = [[UICollectionView alloc] initWithFrame:UIEdgeInsetsInsetRect(self.bounds, self.contentInsets) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.scrollEnabled = YES;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerClass:[ZJSGuideCollectionViewCell class] forCellWithReuseIdentifier:ZJSGuideCollectionViewCellIdentifier];
    }
    return (_collectionView);
}

/**
 *  @brief  页码指示的懒加载
 */
- (UIPageControl *)pageControl {
    if(!_pageControl) {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, 100.0f, 20.0f)];
        _pageControl.backgroundColor = [UIColor clearColor];
        _pageControl.currentPageIndicatorTintColor = UIColorFromHexRGB(0xfc7349);
        _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        _pageControl.currentPage = 0;
    }
    return (_pageControl);
}
#pragma mark -

#pragma mark - <UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return (self.size);
}
#pragma mark -

#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return ([self.imagesNamed count] + 1);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ZJSGuideCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ZJSGuideCollectionViewCellIdentifier forIndexPath:indexPath];
    NSString *imaged = [self.imagesNamed safeObjectAtIndex:indexPath.item];
    cell.imageView.image = imaged ? [UIImage imageNamed:imaged] : nil;
    cell.bottombtn.hidden = ((self.imagesNamed.count == (indexPath.row + 1)) ? NO: YES);
    [cell.bottombtn addTarget:self action:@selector(guideRemove:) forControlEvents:UIControlEventTouchUpInside];
    return (cell);
}
#pragma mark -

#pragma mark - <UICollectionViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat x = scrollView.contentOffset.x;
    if(x < 0) {
        scrollView.contentOffset = CGPointMake(0, scrollView.contentOffset.y);
    }
    _needRemoveSelf = (x > ([self.imagesNamed count] - 1) * scrollView.width);
    self.pageControl.hidden = _needRemoveSelf;
    self.pageControl.currentPage = (NSInteger)((x + scrollView.width / 2.0f) / scrollView.width);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if(_needRemoveSelf) {
        NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] stringObjectForKey:@"CFBundleShortVersionString"];
        [[NSUserDefaults standardUserDefaults] setObject:appVersion ? : @"" forKey:ZJSGuideDidShowKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if(self.dismissBlock) {
            self.dismissBlock();
        }
        [self removeFromSuperview];
    }
}

/**
 *  @brief  立即体验按钮
 */
- (void)guideRemove:(UIButton *)bottomBtn {
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] stringObjectForKey:@"CFBundleShortVersionString"];
    [[NSUserDefaults standardUserDefaults] setObject:appVersion ? : @"" forKey:ZJSGuideDidShowKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if(self.dismissBlock) {
        self.dismissBlock();
    }
    [self removeFromSuperview];
}
#pragma mark -

@end
